package org.dromara.pay.service;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.constant.BusinessConstants;
import org.dromara.business.domain.BusinessConfig;
import org.dromara.business.domain.Goods;
import org.dromara.business.domain.User;
import org.dromara.business.domain.vo.BusinessConfigVo;
import org.dromara.business.service.*;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.websocket.utils.WebSocketUtils;
import org.dromara.pay.domain.TopUp;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 充值成功回调处理器
 *
 * @author zlj
 * @since 2024/5/16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessHandleService {

    private final GoodsService goodsService;
    private final ScheduledExecutorService scheduledExecutorService;
    private final BusinessConfigService businessConfigService;
    private final RoomService roomService;
    private final UserService userService;
    private final UserFlowingService userFlowingService;

    /**
     * 支付业务处理
     *
     * @param topUp 订单信息
     */
    public void businessHandle(TopUp topUp) {
        String orderType = topUp.getOrderType();
        //订单orderId
        String orderJson = topUp.getOrderJson();
        Long userId = topUp.getCreateBy();
        User user = userService.getById(userId);
        //是购买会员
        if (ObjectUtil.equals(orderType, "goods")) {
            processMemberPurchase(user,orderJson,topUp);
        }else if (ObjectUtil.equals(orderType,"purchase")){
            user.setHyNumber(user.getHyNumber()+1);
            boolean b = userService.updateById(user);
        }
    }

    private void processMemberPurchase(User user, String orderJson,TopUp topUp) {
        BusinessConfig businessConfig = businessConfigService.getById(orderJson);
        // 修改用户新增刷新次数和发布次数
        if (!"".equals(orderJson) && orderJson != null) {
            if (businessConfig != null) {

                String remark = businessConfig.getRemark();

                if ( isNumeric(remark)) {
                    int hyNumber = Integer.parseInt(remark);
                    user.setHyNumber(hyNumber);
                }
                int daysToAdd = 0;

                if ( 1 == businessConfig.getSortNo()){
                    daysToAdd = 7;
                }else if ( 2 == businessConfig.getSortNo()){
                    daysToAdd = 30;
                }else if ( 3 == businessConfig.getSortNo()){
                    daysToAdd = 365;
                }else if ( 4 == businessConfig.getSortNo()){
                    daysToAdd = 90;
                }
                // 计算当前时间加上指定天数后的时间
                LocalDateTime currentTime = LocalDateTime.now();
                LocalDateTime newTime = currentTime.plusDays(daysToAdd);
                Date gqTime = Date.from(newTime.atZone(ZoneId.systemDefault()).toInstant());
                user.setGqTime(gqTime);
                boolean b = userService.updateById(user);
            }
        }
    }

    private boolean isNumeric(String str) {
        try {
            // 使用 BigDecimal 的构造函数，它可以处理整数和小数
            new BigDecimal(str);
            return true;
        } catch (NumberFormatException e) {
            // 捕获异常，表示字符串不是有效的数字格式
            return false;
        }
    }
    /**
     * 退款业务处理
     *
     * @param topUp 订单信息
     */
    public void businessRefundHandle(TopUp topUp) {
        //
        String orderType = topUp.getOrderType();
        String orderJson = topUp.getOrderJson();
        Long userId = topUp.getCreateBy();
        if (ObjectUtil.equals(orderType, "goods")) {
            // 1类型业务处理
            Goods goods = goodsService.getById(Long.valueOf(orderJson));
            if (ObjectUtil.isNotNull(goods)) {
                goodsService.removeById(goods);
                scheduledExecutorService.schedule(() -> {
                    WebSocketUtils.sendMessage(UserConstants.SUPER_ADMIN_ID, "订单" + orderJson + "退款已到账");
                }, 0, TimeUnit.SECONDS);
                roomService.send(0L, goods.getCreateBy(), "您发布的任务<" + goods.getName() + ">已退款,请确认");
            }
        } else if (ObjectUtil.equals(orderType, "2")) {
            // 2类型业务处理
        }
    }
}
